import os
import zipfile
# 统一以 bat 启动目录为根目录
base_dir = os.getcwd()
python_dir = os.path.join(base_dir, 'python')
python_zip = os.path.join(base_dir, 'python-3.13.5-embed-amd64.zip')

# 检查是否已解压嵌入式Python
if not os.path.exists(os.path.join(python_dir, 'python.exe')):
    if os.path.exists(python_zip):
        print('正在解压嵌入式Python环境...')
        with zipfile.ZipFile(python_zip, 'r') as zip_ref:
            zip_ref.extractall(python_dir)
        print('解压完成')
    else:
        print('未找到嵌入式Python压缩包，请联系开发者或重新下载完整包。')
        exit(1)

# 自动修复 ._pth 文件
pth_file = os.path.join(python_dir, 'python313._pth')
if os.path.exists(pth_file):
    with open(pth_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    changed = False
    for i, line in enumerate(lines):
        if line.strip() == '#import site':
            lines[i] = 'import site\n'
            changed = True
    if changed:
        with open(pth_file, 'w', encoding='utf-8') as f:
            f.writelines(lines)

import importlib
import sys
import subprocess
import time
import webbrowser


# 自动检测依赖包并自动安装（合并 requirements.txt）
REQUIRED_PACKAGES = [
    'fastapi', 'uvicorn', 'aiohttp', 'openai', 'yaml', 'soundfile', 'pygame', 'psutil', 'pydantic', 'PyQt5', 'bilibili_api', 'requests'
]
# 读取 requirements.txt 并合并
req_file = os.path.join(base_dir, 'requirements.txt')
if os.path.exists(req_file):
    with open(req_file, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#'):
                # 只取包名部分（去除版本号等）
                pkg = line.split('==')[0].split('>=')[0].split('<=')[0].strip()
                if pkg and pkg not in REQUIRED_PACKAGES:
                    REQUIRED_PACKAGES.append(pkg)

missing = []
for pkg in REQUIRED_PACKAGES:
    try:
        importlib.import_module(pkg)
    except ImportError:
        missing.append(pkg)

if missing:
    print("缺少依赖包：" + ', '.join(missing))
    print("正在尝试自动安装依赖，请确保已联网...")
    # 检查 pip 是否可用，否则自动引导安装 pip
    try:
        import pip
    except ImportError:
        # 若无 pip，尝试用 ensurepip 安装
        try:
            import ensurepip
            ensurepip.bootstrap()
            print("已自动安装 pip")
        except Exception as e:
            print("自动安装 pip 失败，请手动安装 pip。", e)
            sys.exit(1)
    # 用 pip 安装缺失依赖
    try:
        subprocess.check_call([
            sys.executable, '-m', 'pip', 'install', *missing, '-i', 'https://pypi.org/simple',
            '--target', os.path.join(os.path.dirname(sys.executable), 'Lib', 'site-packages')
        ])
        print("依赖安装完成，正在重启...")
        os.execv(sys.executable, [sys.executable] + sys.argv)
    except Exception as e:
        print("自动安装依赖失败，请手动安装。", e)
        sys.exit(1)


# 检查 config 目录下关键配置文件是否缺失，缺失则自动补全
config_dir = os.path.join(base_dir, 'config')
examples_dir = os.path.join(config_dir, 'examples')
need_files = [
    'config.yaml',
    'blacklist_uid.txt',
    'blocked_words.txt',
    'punish_words.txt',
    'whitelist_uid.txt',
]
missing = []
for fname in need_files:
    if not os.path.exists(os.path.join(config_dir, fname)):
        missing.append(fname)
if missing:
    print(f"检测到以下配置文件缺失: {', '.join(missing)}，正在自动补全...")
    # 自动调用 tools/init_config.py 进行补全
    init_script = os.path.join(base_dir, 'tools', 'init_config.py')
    subprocess.run([os.path.join(python_dir, 'python.exe'), init_script])
    print("配置文件补全完毕，如需自定义请到 config/ 目录修改。")

# 启动 fastapi_server.py（用嵌入式python）
fastapi_server = os.path.join(base_dir, 'fastapi_server.py')
subprocess.Popen([os.path.join(python_dir, 'python.exe'), fastapi_server])
